const app = getApp()
var sliderWidth = 96

Page({

  data: {
    categoryList: [],
    activeIndex: 0,
    sliderOffset: 25,
    sliderLeft: 0,
    page: 1,
    videoList: [],
    imageUrl: app.globalData.imageUrl,
    flags: {},
    sysWidth:0,
    searchWord: "搜索",
    inputValue: '', //搜索的内容
    collectList:[], // 收藏按钮列表
  },

  onLoad: function () {
    var that = this
    this.setData({
      page: 1
    })
    wx.showLoading({
      title: '加载数据中...',
      success: function() {
        that.getConfig()
        that.getCategoryList()
        that.getVideoByType('new')
      }
    })
    // 获取系统信息
    wx.getSystemInfo({
      success: res => {
        that.setData({
          sysWidth: res.windowWidth
        })
      }
    })
    this.getSearchWord()
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
  },

  getConfig: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'user/config?version=' + app.globalData.version,
      success: function(res) {
        if (res.data.data) {
          that.setData({
            flags: res.data.data
          })
        }
      }
    })
  },

  // 获取分类列表
  getCategoryList: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'videos/get_recommend_type?version=' + app.globalData.version,
      success: function(res) {
        var categoryList = res.data.data
        that.setData({
          categoryList: categoryList
        })
        wx.getSystemInfo({
          success: function(res) {
            that.setData({
              sliderLeft: (res.windowWidth / categoryList.length - sliderWidth) / 2
            })
          }
        })
      }
    })
  },

  // tab点击事件
  tabClick: function(e) {
    // 页面跳到最上
    wx.pageScrollTo({
      scrollTop: 0,
    })
    var that = this    
    var id = e.currentTarget.dataset.id
    var value = e.currentTarget.dataset.type
    this.setData({
      page: 1,
      activeIndex: id
    })
    wx.showLoading({
      title: '加载数据中...',
      success: function() {
        that.getVideoByType(value)
        that.setData({
          collectList:[]
        })
      },
    })
  },

  // 处理收藏逻辑
  collect: function(e) {
    var videoId = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    if (this.data.collectList[index]) {
      this.collectRequest(videoId, 'del')
    } else {
      this.collectRequest(videoId, 'add')
    }
  },
  // 判断是否收藏
  getIsCollect: function(videoId) {
    this.collectRequest(videoId, 'fetch')
  },
  // 收藏相关网络操作
  collectRequest: function(id, cType) {
    var that = this
    var url = app.globalData.url + 'user/'
    var isDel = true
    switch (cType) {
      case 'add':
        url = url + 'add_favor'
        break
      case 'del':
        url = url + 'del_favor'
        isDel = false
        break
      case 'fetch':
        url = url + 'fetch_favor'
        break
    }
    wx.request({
      url: url,
      method: 'POST',
      data: {
        version: app.globalData.version,
        openid: app.globalData.openId,
        video_id: id
      },
      success: function(res) {
        if (res.data.msg == 'ok') {
          let list = that.data.videoList
          for(let i = 0 ; i < list.length ; i ++){
            if(list[i].id == id){
              var nowitem = 'collectList[' + i + ']'
              that.setData({
                [nowitem]: isDel
              })
              return
            }
          }
        }
      }
    })
  },

  // 上拉加载
  onReachBottom: function() {
    var that = this
    var data = this.data
    wx.showLoading({
      title: '加载数据中...',
      success: function() {
        var remmondCategory = 'new'
        switch (data.activeIndex) {
          case 0:
            remmondCategory = 'new'
            break
          case 1:
            remmondCategory = 'hot'
            break
          case 2:
            remmondCategory = 'collect'
            break
          case 3:
            remmondCategory = 'share'
            break
        }
        that.getVideoByType(remmondCategory)
      },
    })
  },

  // 获取formId
  formSubmit: function(e) {
    let formId = e.detail.formId
    let id = e.currentTarget.dataset.id
    if(app.globalData.isFirstOpen){
      this.uploadFormid(formId)
    }
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id
    })
  },

  onShareAppMessage(res) {
    // 统计分享次数
    wx.request({
      url:  app.globalData.url + 'user/handle_share',
      data: {
        openid: app.globalData.openId,
        video_id: res.target.dataset.id
      },
      method: 'POST',
      success: (res)=>{
        wx.showToast({
          title: '分享成功',
          icon: 'none',
          image: '',
          duration: 1500,
          mask: false,
        })
      }
    })
    
    var sharetitle = res.target.dataset.title
    var id = res.target.dataset.id
    var cover = res.target.dataset.cover
    return {
      title: sharetitle,
      imageUrl: cover,
      path: '/pages/detail/detail?id=' + id,
    }
  },

  // 根据分类id获取随机视频
  getVideoByType: function (typeValue) {
    var that = this
    wx.request({
      url: app.globalData.url + 'videos/get_videolist_by_recommend_type',
      data:{
        openid:app.globalData.openId,
        type:typeValue,
        page:that.data.page,
        version:app.globalData.version
      },
      method:"POST",
      success: function (res) {
        var list = res.data.data
        if(res.data.msg == 'list'){
          that.setData({
            page: that.data.page + 1,
            videoList: that.data.page == 1 ? list : that.data.videoList.concat(list)
          })
          for(let i = 0 ; i < list.length ; i ++){
            that.setData({
              collectList: that.data.collectList.concat(list[i].favor)
            })
          }
          wx.hideLoading()
        }else{
          wx.hideLoading()
          wx.showToast({
            title: '已经到底啦~',
            icon: 'none',
            image: '',
            duration: 1500,
            mask: false,
          })
        }
      },
      fail: function (e) {
        console.log(e)
      }
    })
  },

  // 上传formid
  uploadFormid :function(formid){
    var that = this
    //通过网络请求发送openid和formIds到服务器
    wx.request({
      url: app.globalData.url + 'user/handler_formid',
      method: 'POST',
      data: {
        ghid: 'gh_91d384b2777f',
        openid: app.globalData.openId,
        formid: formid
      },
      success: function (res) {
        if(res.data.msg == 'ok'){
          app.globalData.isFirstOpen = false
        }
      }
    })
  },

  // 获取搜索默认词
  getSearchWord: function(){
    var that = this
    wx.request({
      url: app.globalData.url +'videos/query_keyword',
      method: 'GET',
      success: (res)=>{
        that.setData({
          searchWord: res.data.data,
          inputValue: res.data.data
        })
      },
    })
  },
  // 绑定搜索框的文本
  inputBind: function(event) {
    this.setData({
        inputValue: event.detail.value
    })
  },
  // 搜索
  search: function(){
    wx.navigateTo({
      url: '/pages/search/search?keyword='+ this.data.inputValue,
    })
  },
})